package com.dinero.pagecontents.activity;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.dinero.pagecontents.R;
import com.dinero.pagecontents.fragment.OrderDetailFragment;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.ArrayList;

public class OrderListActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_list);
        initView();
    }

    private TabLayout tabLayout;
    private ViewPager2 viewPager2;

    private ArrayList<Fragment> fragments;
    private ArrayList<String> mTitleDatas = new ArrayList<>();
    private TabLayoutMediator mediator;

    private void initView() {
        tabLayout = findViewById(R.id.tab_layout);
        viewPager2 = findViewById(R.id.view_pager);
        mTitleDatas.add("Todos");
        mTitleDatas.add("En proceso");
        mTitleDatas.add("Préstamos");
        mTitleDatas.add("Pagados");
        tabLayout.addTab(tabLayout.newTab().setText("Todos"));
        tabLayout.addTab(tabLayout.newTab().setText("En proceso"));
        tabLayout.addTab(tabLayout.newTab().setText("Préstamos"));
        tabLayout.addTab(tabLayout.newTab().setText("Pagados"));

        //禁用预加载
        viewPager2.setOffscreenPageLimit(ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT);
        //Adapter
        viewPager2.setAdapter(new FragmentStateAdapter(getSupportFragmentManager(), getLifecycle()) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                //FragmentStateAdapter内部自己会管理已实例化的fragment对象。
                // 所以不需要考虑复用的问题
                return OrderDetailFragment.newInstance();
            }

            @Override
            public int getItemCount() {
                return 4;
            }
        });

        mediator = new TabLayoutMediator(tabLayout, viewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                tab.setText(mTitleDatas.get(position));
            }
        });
        //要执行这一句才是真正将两者绑定起来
        mediator.attach();
    }
}